#!/usr/bin/python
# -*- coding: UTF-8 -*-
# @author:qiaofinn
# @file:serializersfield.py
# @time:2020/09/28

from django.utils import timezone
from rest_framework import serializers


def getAttributeValue(instance, obj):
    if '.' in instance.source:
        k = instance.source.split('.')
        for i in range(len(k)):
            if hasattr(obj, k[i]):
                obj = getattr(obj, k[i])
        val = obj
    else:
        val = getattr(obj, instance.source)
    return val


class DelayTimeCharField(serializers.CharField):
    def get_attribute(self, obj):
        return obj

    def to_representation(self, obj):
        val = getAttributeValue(self, obj)
        delay = timezone.now() - val

        if delay:
            if delay.days and delay.days < 0:
                delay = u'刚刚'
            elif delay.days and delay.days > 0:
                delay = u'{}天前'.format(delay.days)
            elif delay.seconds > 60:
                delay = delay.seconds / 60
                if delay < 60:
                    delay = u'{}分钟前'.format(int(delay))
                elif delay < 60 * 24:
                    delay = u'{}小时前'.format(int(delay / 60))
            else:
                delay = u'刚刚'
        else:
            delay = u''
        return delay


class BooleanCharField(serializers.BooleanField):
    def get_attribute(self, instance):
        return instance

    def to_representation(self, obj):
        val = getAttributeValue(self, obj)
        return '是' if val else '否'


class BooleanCheckCharField(serializers.BooleanField):
    def get_attribute(self, instance):
        return instance

    def to_representation(self, obj):
        val = getAttributeValue(self, obj)
        return [1] if val else []


class ImageUploadCharField(serializers.CharField):
    def get_attribute(self, instance):
        return instance

    def to_representation(self, obj):
        val = getAttributeValue(self, obj)
        if val:
            return [{'name': val.file_path, 'uid': val.id, 'old': True,
                     'thumbUrl': val.get_url()}]
        return []
